package com.wdb.modules.system.rest;

import cn.hutool.core.collection.CollectionUtil;
import com.wdb.exception.BadRequestException;
import com.wdb.modules.system.domain.Dept;
import com.wdb.modules.system.domain.vo.DeptQueryCriteria;
import com.wdb.modules.system.service.DeptService;
import com.wdb.utils.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: wendaobai@qq.com
 * @date: 2024/1/24 0024 14:36
 */
@Slf4j
@Api("系统--部门")
@RestController
@RequestMapping("/api/dept")
@RequiredArgsConstructor
public class DeptController {
  private final DeptService deptService;

  @ApiOperation("部门列表")
  @GetMapping
  public ResponseEntity<PageResult<Dept>> queryDept(DeptQueryCriteria criteria)
      throws IllegalAccessException {
    PageResult<Dept> pageResult = deptService.findAll(criteria, true);
    return new ResponseEntity(pageResult, HttpStatus.OK);
  }

  @ApiOperation("新增部门")
  @PostMapping
  public ResponseEntity<Object> createDept(@Validated @RequestBody Dept resources)
      throws Exception {
    log.info("createDept:{}", resources);
    if (resources.getId() != null) {
      throw new BadRequestException("参数错误！");
    }
    deptService.create(resources);
    return new ResponseEntity<>("success", HttpStatus.CREATED);
  }

  /**
   * 删除部门， tip: 需要递归删除子节点
   *
   * @param ids
   * @return
   */
  @ApiOperation("删除节点")
  @DeleteMapping
  public ResponseEntity<Object> deleteDept(@RequestBody Set<Long> ids) throws Exception {
    HashSet<Dept> depts = new HashSet<>();
    // 先查询所有要删除的节点，递归删除
    for (Long id : ids) {
      depts.add(deptService.getById(id));
      List<Dept> deptList = deptService.findByPid(id);
      if (CollectionUtil.isNotEmpty(deptList)) {
        depts = deptService.getDeleteDepts(deptList, depts);
      }
    }
    log.info("depts:{}", depts);
    deptService.delete(depts);
    return new ResponseEntity<>("success", HttpStatus.OK);
  }

  @ApiOperation("导出部门信息")
  @GetMapping("/download")
  public void exportDept(HttpServletResponse response, DeptQueryCriteria criteria)
      throws Exception {
    PageResult<Dept> deptPageResult = deptService.findAll(criteria, false);
    List<Dept> deptList = deptPageResult.getContent();
    deptService.download(deptList, response);
  }

  @ApiOperation("查询部门:根据ID获取同级与上级数据")
  @PostMapping("/superior")
  public ResponseEntity<Object> getDeptSuperior(
      @RequestBody List<Long> ids, @RequestParam(defaultValue = "false") Boolean exclude) {

    return new ResponseEntity<>(HttpStatus.OK);
  }
}
